# -*- coding: utf-8 -*- 
# @Time : 2021/3/25 21:39 
# @Author : Dong 
# @File : demo_one.py
import json
import re
import time
from multiprocessing import Pool

import requests
from requests.exceptions import RequestException   # 抓取报错

def get_one_page(url,headers):
    try:
        response = requests.get(url,headers=headers)
        time.sleep(1)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None

def parse_one_page(html):
    pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',re.S)
    items = re.findall(pattern,html)
    for item in items:
        yield {
            'id':item[0],
            'image':item[1],
            'name':item[2],
            'actor':item[3].strip()[3:],
            'time':item[4][5:],
            'score':item[5]+item[6]
        }

def save(content):
    with open('movie.txt','a+',encoding='utf-8')as book:
        book.write(json.dumps(content,ensure_ascii=False) + '\n')

def main(index):
    url = 'https://maoyan.com/board/4?offset=' + str(index)
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'}
    html = get_one_page(url,headers)
    for item in parse_one_page(html):
        print(item)
        save(item)


if __name__ == '__main__':
    # for i in range(10):
    #     main(i*10)
    pool = Pool()
    pool.map(main,[i*10 for i in range(10)])

